package com.dacool.fragment;

import static com.dacool.util.ViewUtils.rp;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.dacool.app.sale.R;
import com.dacool.helper.DaCoolHelper;
import com.dacool.helper.DaCoolHelper.CartItemObserver;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.CreateOrderRequest;
import com.dacool.model.CartItem;
import com.dacool.model.DCUser;
import com.dacool.util.ViewUtils;
import com.dacool.view.TitleItem;
import com.dacool.view.holder.CartItemCell;
import com.lidroid.xutils.BitmapUtils;

public class CartFragment extends BaseFragment implements CartItemObserver,
		OnClickListener {

	private ListView productlist;
	private TextView priceLabel;
	private Button purchaseButton;
	private Button goBuyButton;
	private RelativeLayout emptyView;
	private ArrayAdapter<CartItem> mAdapter;
	private ArrayList<CartItem> mItems;
	private BitmapUtils bmUtils;
	boolean editing = false;

	private TextView titleView;

	private Button rightButton;

	private RelativeLayout buyArea;

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		RelativeLayout rl = new RelativeLayout(getActivity());
		rl.setBackgroundColor(Color.WHITE);
		productlist = new ListView(getActivity());
		emptyView = new RelativeLayout(getActivity());
		TextView tv = new TextView(getActivity());
		tv.setText("购物车还是空的");
		tv.setId(10086);
		LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		param.addRule(RelativeLayout.CENTER_HORIZONTAL);
		param.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		param.topMargin = ViewUtils.rp(100);
		emptyView.addView(tv, param);
		goBuyButton = new Button(getActivity());
		goBuyButton.setText("去逛逛");
		goBuyButton.setBackgroundResource(R.drawable.roundbutton);
		goBuyButton.setTextColor(Color.WHITE);
		goBuyButton.setOnClickListener(this);
		param = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		param.addRule(RelativeLayout.BELOW, tv.getId());
		param.addRule(RelativeLayout.CENTER_IN_PARENT);
		param.topMargin = ViewUtils.rp(10);
		emptyView.addView(goBuyButton, param);
		emptyView.setVisibility(View.GONE);

		param = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		rl.addView(emptyView, param);

		param = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		rl.addView(productlist, param);
		productlist.setEmptyView(emptyView);
		productlist.setBackgroundColor(Color.WHITE);

		buyArea = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(
				R.layout.cart_buyarea, null);
		purchaseButton = ViewUtils.findViewById(buyArea, R.id.buyButton);
		priceLabel = ViewUtils.findViewById(buyArea, R.id.priceLabel);

		purchaseButton.setOnClickListener(this);

		buyArea.setPadding(rp(30), rp(10), rp(30), 0);
		productlist.addFooterView(buyArea);

		return rl;
	}

//	@Override
//	protected boolean showDefaultLeftButton() {
//		// TODO Auto-generated method stub
//		return true;
//	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		bmUtils = new BitmapUtils(getActivity());
		bmUtils.configDiskCacheEnabled(true);
		bmUtils.configDefaultLoadingImage(R.drawable.bannerimg);
		bmUtils.configDefaultLoadFailedImage(R.drawable.bannerimg);
		bmUtils.configDefaultBitmapConfig(Config.ARGB_8888);
		mItems = DaCoolHelper.sharedInstance().getCartItems();
		DaCoolHelper.sharedInstance().addCartItemObserver(this);
		mAdapter = new ArrayAdapter<CartItem>(getActivity(), 0) {
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return mItems != null ? mItems.size() : 0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				if (convertView == null) {
					View view = CartItemCell.createFromInflator(LayoutInflater
							.from(getActivity()));
					CartItemCell cell = (CartItemCell) view.getTag();
					cell.btnAdd.setOnClickListener(CartFragment.this);
					cell.btnRemove.setOnClickListener(CartFragment.this);
					cell.buttonDelete.setOnClickListener(CartFragment.this);
					convertView = view;
				}
				CartItem item = mItems.get(position);
				CartItemCell cell = (CartItemCell) convertView.getTag();
				if (item.getProduct().getIconUrl() != null) {
					bmUtils.display(cell.iconView, item.getProduct()
							.getIconUrl());
				}
				cell.titleLabel.setText(item.getProduct().getName());
				cell.priceLabel.setText(String.format("%d x ¥%.2f",
						item.getAmount(), item.getProduct().getPrice()));
				cell.amountEdit.setText("" + item.getAmount());
				cell.btnAdd.setTag(Integer.valueOf(position + 1));
				cell.btnRemove.setTag(Integer.valueOf(-position - 1));// avoid 0
				cell.buttonDelete.setTag(new int[] { position, 0 });
				cell.setEditing(editing);
				return convertView;
			}

		};

		productlist.setAdapter(mAdapter);
		setPriceLabel();
	}

	private void setPriceLabel() {
		double price = 0;
		if (mItems != null) {
			for (CartItem item : mItems) {
				price += item.getProduct().getPrice() * item.getAmount();
			}
		}
		priceLabel.setText(String.format("¥ %.2f", price));
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub

		super.onResume();

	}

	@Override
	public void cartItemsChanged() {
		ViewUtils.runInMainThread(new Runnable() {

			@Override
			public void run() {

				mItems = DaCoolHelper.sharedInstance().getCartItems();
				emptyView.setVisibility(View.GONE);
				productlist.setVisibility(View.VISIBLE);
				mAdapter.notifyDataSetChanged();
				setPriceLabel();
			}
		});

	}

	@Override
	public TitleItem getTitleItem() {
		// TODO Auto-generated method stub
		if (getActivity() == null)
			return null;
		if (titleView == null) {
			titleView = new TextView(getActivity());
			titleView.setBackgroundColor(Color.TRANSPARENT);
			titleView.setTextColor(Color.WHITE);
			titleView.setText("购物车");
			titleView.setTextSize(26);
			titleView.setTypeface(null, Typeface.BOLD);
			mTitleItem = new TitleItem();
			mTitleItem.view = titleView;
		}

		return mTitleItem;
	}

	@Override
	public TitleItem getRightItem() {
		if (getActivity() == null)
			return null;
		if (rightButton == null) {
			rightButton = new Button(getActivity());
			rightButton
					.setBackgroundResource(R.drawable.button_green_white_border);
			rightButton.setTextColor(Color.WHITE);
			rightButton.setText("编辑");
			rightButton.setTextSize(15);
			rightButton.setPadding(0, 0, 0, 0);
			rightButton.setOnClickListener(this);
			mRightItem = new TitleItem();
			mRightItem.view = rightButton;
			mRightItem.width = rp(80);
			mRightItem.height = rp(30);
//			Log.d("test", "create button:" + rightButton.getWidth()
//					+ ",height:" + rightButton.getHeight());
		}
		return mRightItem;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == rightButton) {
			editing = !editing;
			mAdapter.notifyDataSetChanged();
		} else if (v == goBuyButton) {
			getContainerActivity().getMainActivity().setCurrentTab(2,ProductListFragment.class);

		} else if (v == purchaseButton) {
			/**
			 * { “success":”true”,”ordered”:”2412”} 
			 */

			OrderFragment fragement = new OrderFragment();
			fragement.setOrderItems(mItems);
			getContainerActivity().addFragment(fragement);

		} else if (v.getTag() instanceof Integer) {
			int value = ((Integer) v.getTag()).intValue();
			int pos = value > 0 ? value - 1 : -value - 1;
			CartItem item = mItems.get(pos);
			if (value < 0 && item.getAmount() > 1) {
				DaCoolHelper.sharedInstance().removeItem(item, 1);
			} else if (value > 0) {
				DaCoolHelper.sharedInstance().addItem(item, 1);
				// item.setAmount(item.getAmount() + 1);
			}
			// mAdapter.notifyDataSetChanged();

		} else if (v.getTag() != null && v.getTag().getClass().isArray()) {
			int[] array = (int[]) v.getTag();
			int pos = array[0];
			CartItem item = mItems.get(pos);
			DaCoolHelper.sharedInstance().removeItem(item, item.getAmount());
			// mItems.remove(pos);
			// mAdapter.notifyDataSetChanged();
		}
		super.onClick(v);
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "购物车";
	}
}
